Resetting or Clearing RTK Query Cache Programmatically
RTK Query provides utilities to reset or clear cached data programmatically. This is helpful when users log out, switch accounts, or when you need to force-refresh application state.
1. api.util.resetApiState(): Clears all cached query data, mutations, and subscriptions for the entire API slice.
2. api.util.invalidateTags(): Invalidates specific cached data associated with provided tags, prompting them to refetch.
3. Store Reset: You can also manually reset the Redux store if you want to clear all app state, including RTK Query cache.
In this example, when a user logs out, resetApiState() clears all cached queries and mutations, ensuring that sensitive or user-specific data is removed.
If your endpoints use tag-based caching, invalidating tags will automatically trigger refetches for related queries without clearing the entire cache.
- On User Logout: To clear all user-specific cached data.
- On Environment Change: When switching between tenants or servers.
- For Debugging or State Reset: To force a clean app state for troubleshooting.
Using resetApiState() or invalidateTags() gives you fine control over cache management, keeping your app’s data consistent and secure.